package com.gopay.scheduler.job;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.DrawOpType;
import com.gopay.common.constants.trans.PayBankOpType;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.cps.cbrmb.Tran01721PortalVO;
import com.gopay.common.domain.cps.gp.GP01301VO;
import com.gopay.common.domain.cps.transfer.Tran00700VO;
import com.gopay.common.domain.cps.transfer.Tran00800VO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;

/**
 * 跨境人民币出口自动结算处理银企直连成功后的乐观锁异常Job
 * @CbRmbOutAutoSettleOptimiLockJob.java
 * @author qld
 * @2016年7月13日 上午9:27:34  www.gopay.com.cn Inc.All rights reserved.
 */
public class CbRmbOutAutoSettleOptimiLockJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;
    
    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;
    
    @Override
    public void doJobInternal() {
        
        
        //自动结算之重做乐观锁异常订单
        doAutoSettleRedoOptimiLockOrder(); 
        
        
        logger.error("跨境的AutoSettleManualLaunchOrderJob------start------");
        //自动结算之手动发起订单
        doAutoSettleManualLaunchOrder();
        
        logger.error("跨境的AutoSettleManualLaunchOrderJob------end------");
    }
    
    /**
     * 自动结算之重做乐观锁异常订单
     */
    private void doAutoSettleRedoOptimiLockOrder(){
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select m.gopay_order_id,m.gopay_int_txn_cd from cps_gen_main_order m  ");
        sb.append(" left join cps_gen_pay_order p on p.gopay_order_id=m.gopay_order_id ");
        sb.append("  where 1=1 ");
        sb.append("  and p.auto_settle='1' ");
        sb.append("  and m.accounting_point='1' ");
        sb.append("  and m.txn_sta_cd="+TxnStaCode.TXN_STA_CD_90003.value);
        sb.append("  and m.gopay_int_txn_cd in ('01721') ");
        sb.append("  and p.cust_audit_time>= to_timestamp(:preMonth, 'yyyymmdd') ");
        
               
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        //日期T-30
        String preMonth=DateUtils.format(calendar.getTime(), "yyyyMMdd");
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("preMonth", preMonth);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        String gopayOrderId,intTxnCd;
        Object paramVo;
        CPSResponse response;
        if (rsList != null && rsList.size() > 0) {
            logger.error("OptimisticLockOrder--rsList.size="+rsList.size());
            
            for (Object[] arr : rsList) {
                gopayOrderId=(String) arr[0];
                intTxnCd=(String) arr[1];
                
                // 封装cps请求参数vo
                paramVo = buildCallCpsParamOfOptimiLock(gopayOrderId, intTxnCd);
                
                try {
                    logger.error("callCps-------gopayOrderId="+gopayOrderId+",intTxnCd="+intTxnCd);
                    // 调用cps
                    response=callCPSHelper.callCbRmbByVOTicket(paramVo);
                    if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                        logger.error("------调用cps返回异常  response="+response.getRespCode());
                    }

                } catch (Exception e) {
                    // 吃掉所有异常
                    logger.error("callByVOTicket Error", e);
                }
            }
        }
    }
    
    /**
     * 封装cps请求参数vo
     * 
     * @param gopayOrderId
     * @param intTxnCd
     * @return
     */
    private Object buildCallCpsParamOfOptimiLock(String gopayOrderId,String intTxnCd) {
            Object obj = null;
            Tran01721PortalVO paramVo = new Tran01721PortalVO();
            paramVo.setGopayOrderId(gopayOrderId);
            paramVo.setOpType(PayBankOpType.AUTO_SETTLE_REDO_OPTIMI_LOCK_ORDER);

            obj = paramVo;
  

        return obj;
    }
    
    /**
     * 自动结算之手动发起订单
     */
    private void doAutoSettleManualLaunchOrder(){
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select m.gopay_order_id,m.gopay_int_txn_cd from cps_gen_main_order m  ");
        sb.append(" left join cps_gen_pay_order p on p.gopay_order_id=m.gopay_order_id ");
        sb.append("  where 1=1 ");
        sb.append("  and p.PAY_STAT='06' ");
        sb.append("  and p.auto_settle='1' ");
        //sb.append("  and m.accounting_point='1' ");//我也不知道要不要这个条件了
        sb.append("  and m.txn_sta_cd="+TxnStaCode.TXN_STA_CD_30000.value);
        sb.append("  and m.gopay_int_txn_cd in ('01721') ");
        sb.append("  and p.cust_audit_time>= to_timestamp(:preMonth, 'yyyymmdd') ");
        
               
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -30);
        //日期T-30
        String preMonth=DateUtils.format(calendar.getTime(), "yyyyMMdd");
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("preMonth", preMonth);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        String gopayOrderId,intTxnCd;
        Object paramVo;
        CPSResponse response;
        if (rsList != null && rsList.size() > 0) {
            logger.error("doAutoSettleManualLaunchOrder--rsList.size="+rsList.size());
            
            for (Object[] arr : rsList) {
                gopayOrderId=(String) arr[0];
                intTxnCd=(String) arr[1];
                
                // 封装cps请求参数vo
                paramVo = buildCallCpsParamOfManualLaunch(gopayOrderId, intTxnCd);
                
                try {
                    logger.error("doAutoSettleManualLaunchOrder callCps-------gopayOrderId="+gopayOrderId+",intTxnCd="+intTxnCd);
                    // 调用cps
                    response=callCPSHelper.callCbRmbByVOTicket(paramVo);
                    if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                        logger.error("------doAutoSettleManualLaunchOrder 调用cps返回异常  response="+response.getRespCode());
                    }

                } catch (Exception e) {
                    // 吃掉所有异常
                    logger.error("doAutoSettleManualLaunchOrder callByVOTicket Error", e);
                }
            }
        }
    }
    
    private Object buildCallCpsParamOfManualLaunch(String gopayOrderId,String intTxnCd) {
        Object obj = null;
       
            Tran01721PortalVO paramVo = new Tran01721PortalVO();
            paramVo.setGopayOrderId(gopayOrderId);
            paramVo.setOpType(PayBankOpType.AUTO_SETTLE_MANUAL_BCD_LOCK_DEAL);

            obj = paramVo;
    

        return obj;
    }

}
